# -*- coding: utf-8 -*-

import os,json


FILE_DIR = 'lmch'
MAINFEST = '__openerp__.py'

# mainfest config
AUTHOR = 'lmch'
APPLICATION = 1 


def mainfest_filter(file_path):
    info = {}
    with open(file_path, 'rb') as f:
        info.update(eval(f.read()))
        
    info['author'] = AUTHOR
    info['application'] = APPLICATION
    
    with open(file_path, 'wb') as f:
        f.write('# -*- coding: utf-8 -*-'+'\r\n')
        info = json.dumps(info, indent=4)
        f.write(info)
    

def get_file_paths(file_dir):
    
    file_paths = []
    
    for root, dirs, files in os.walk(file_dir):
        for file_name in files:
            file_path = os.path.join(root, file_name)
            file_paths.append(file_path)
            
    return file_paths


def replace_file_content(replace_dict, file_paths):
        
    origin_content = ''
    replace_content = ''
    for file_path in file_paths:
        with open(file_path, 'rb') as f:
            origin_content  = f.read()
            for origin_str,replace_str in replace_dict.items():
                replace_content = origin_content.replace(origin_str, replace_str)
                origin_content = replace_content
                
        with open(file_path, 'wb') as f:
            f.write(replace_content)
            
def filter_files(file_paths):
    
    file_filters = {MAINFEST:mainfest_filter}
    for file_path in file_paths:
        file_name = os.path.basename(file_path)
        if file_filters.has_key(file_name):
            file_filters[file_name](file_path)
            
def generate_replace_dict(module_name):
    
    replace_dict = {'lmch':'', 'Lmch':''}
    
    replace_dict['lmch'] = module_name
    controller_name = module_name[0].upper()+module_name[1:]
    replace_dict['Lmch'] = controller_name
    
    return replace_dict
            
def handle_files(args):
    
    module_name = args['module_name']
    
    file_paths = get_file_paths(FILE_DIR)
    replace_dict = generate_replace_dict(module_name)
    
    replace_file_content(replace_dict, file_paths)
    filter_files(file_paths)
    
    # 重命名包名
    os.rename(FILE_DIR, module_name)
            
            
if __name__ == "__main__":
    #file_path = 'lmch/__openerp__.py'
    #mainfest_filter(file_path)
    
    #info = {}
    #with open('lmch/__openerp__.py') as f:
        #info.update(eval(f.read()))
    #print info
    
    #file_path = 'lmch/__openerp__.py'
    #print os.path.basename(file_path)
    
    #l = 'lmch'
    #_l = l[0].upper()+l[1:]
    #print _l
    import sys
    
    args = {}
    module_name = sys.argv[1]
    if not module_name:
        print u'模块名称不能为空'
    else:
        args['module_name'] = module_name
        handle_files(args)